﻿using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;
using System.Collections.Generic;
using System;
//培训课程，课程资料 关联表
namespace IPR_WebApi.Controllers
{
    public class TrainCourseFilesController : ApiController
    {
        [HttpPost]
        [Route("api/TrainCourseFiles/Search")]
        public IHttpActionResult Search([FromBody]string swhere)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                swhere = swhere ?? string.Empty;
                //int startindex = (page - 1) * limit + 1;
                //int endindex = page * limit;
                if (!string.IsNullOrWhiteSpace(swhere))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = " 1=1 ";
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "TCOID")//培训课程 id
                        {
                            if ((item.Value != "") && (item.Value != null))
                            { swhere += $" AND TCOID ={item.Value} "; }
                        }
                    }
                }
                bool blExist = false;
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().GetList(swhere);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowCount;
                            blExist = true;
                        }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText() + exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }


        [HttpGet]
        [Route("api/TrainCourseFiles/GetContentForTCOID")]
        public IHttpActionResult GetContentForTCOID(string TCOID)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().GetList(" TCOID="+TCOID);
                if (dsSearch != null)
                {
                    if (dsSearch.Tables.Count > 0)
                    {
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "内部请求出错 " + exc.Message;
            }
            return Json(resultMsg);
        }


        [HttpGet]
        [Route("api/TrainCourseFiles/GetContent")]
        public IHttpActionResult GetContent(string TPID)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().GetTContent(TPID);
                if (dsSearch != null)
                {
                    if (dsSearch.Tables.Count > 0)
                    {
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        { 
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "内部请求出错 " + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 乘务员学习内容查询
        /// </summary>
        /// <param name="swhere"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainCourseFiles/StudyContentSearch")]
        public IHttpActionResult StudyContentSearch(string swhere, int page, int limit)
        {
            string UserID = "";
            string UserName = "";
            string StartDate = "";
            string EndDate = "";
            string searchLevel = "";
            if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
            {
                Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                swhere = string.Empty;
                foreach (var item in jsonObject)
                {
                    if (item.Key == "UserID")
                    {
                        if (item.Value != "")
                            UserID = item.Value;
                    }
                    if (item.Key == "UserName")
                    {
                        if (item.Value != "")
                            UserName = item.Value;
                    }
                    if (item.Key == "StartDate")
                    {
                        if (item.Value != "")
                            StartDate = item.Value;
                    }
                    if (item.Key == "EndDate")
                    {
                        if (item.Value != "")
                            EndDate = item.Value;
                    }
                    if (item.Key == "searchLevel")
                    {
                        if (item.Value != "")
                            searchLevel = item.Value;
                    }
                }
            }

            ResultMsg resultMsg = new ResultMsg();
            int startindex = (page - 1) * limit + 1;
            int endindex = page * limit;
            string strSql = "";
            string strSqlpage = "";
            string strSqlCount = "select count(*) from ";
            string strSqlpageHead = "select * from ";
            strSql = " ( SELECT ROW_NUMBER() OVER(order by StudyDateTime) as Row," +
                " DepName,T2.UserID,T3.UserName,CONVERT(nvarchar(11), StudyDateTime, 20) as StudyDateTime,TContent,CRID,TCMark   from TrainCourseFiles T1 " +
                " LEFT JOIN TrainStudyLog T2 ON T1.TCOID = T2.TCOID " +
                " LEFT JOIN UserInfo T3 ON T2.UserID = T3.UserID " +
                " LEFT JOIN Dep T4 ON T3.DeptID = T4.DepID " +
                " WHERE 1 = 1 " +
                " AND CONVERT(nvarchar(11),StudyDateTime,20) BETWEEN '" + StartDate + "' AND '" + EndDate + "'";
            if(UserID!="")
            {
                strSql += " AND T2.UserID = '"+UserID+"'";
            }
            if (UserName != "")
            {
                strSql += " AND T3.UserName LIKE '%"+UserName+"%'";
            }
            if(LoginUser.DepLevel==0)
            {
                //--统计所有车间人员学习内容
            }
            else if(LoginUser.DepLevel==1)
            {
                //统计所有车队人员学习内容
                strSql += " AND T4.DepPID="+LoginUser.DepID.ToString();
            }
            else if(LoginUser.DepLevel == 2)
            {
                //统计当前车队人员
                strSql += " AND T4.DepID=" + LoginUser.DepID.ToString();
            }
            strSql += " ) TT ";

            strSqlpage = String.Format(" WHERE TT.Row between {0} and {1}", startindex, endindex); 
            try
            {

                int rowcount = 0;
                rowcount= new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().GetSqlCount(strSqlCount+strSql);
                bool blExist = false;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().StudyContentSearch(strSqlpageHead+strSql);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowcount;
                            blExist = true;
                        }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText() + exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }


        /// <summary>
        /// 车队学习内容统计
        /// </summary>
        /// <param name="swhere"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainCourseFiles/CheduiStudyContentSearch")]
        public IHttpActionResult CheduiStudyContentSearch(string swhere, int page, int limit)
        {

            string StartDate = "";
            string EndDate = "";
            string chedui = "";
            //string searchLevel = "";
            if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
            {
                Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                swhere = string.Empty;
                foreach (var item in jsonObject)
                {

                    if (item.Key == "StartDate")
                    {
                        if (item.Value != "")
                            StartDate = item.Value;
                    }
                    if (item.Key == "EndDate")
                    {
                        if (item.Value != "")
                            EndDate = item.Value;
                    }
                    if (item.Key == "chedui")
                    {
                        if (item.Value != "")
                            chedui = item.Value;
                    }
                }
            }

            ResultMsg resultMsg = new ResultMsg();
            int startindex = (page - 1) * limit + 1;
            int endindex = page * limit;
            string strSql = "";
            string strSqlpage = "";
            //var depLevel = LoginUser.DepLevel; //一车间：1      北线：2
            //var depID = LoginUser.DepID;  //一车间：3     北线：10

            //if (chedui=="0")
            //{
            //    strSql = "select * from (select row_number() over(order by StartDateTime desc) as rowNumber,* from V_CheduiContentSearch where isCheck=1 and  (CONVERT(nvarchar(11),StartDateTime,20) BETWEEN '" + StartDate + "' and '" + EndDate + "')";
            //}
            //else
            //{
            //    strSql = "select * from (select row_number() over(order by StartDateTime desc) as rowNumber,* from V_CheduiContentSearch where isCheck=1 and DepID='" + chedui + "' and (CONVERT(nvarchar(11),StartDateTime,20) BETWEEN '" + StartDate + "' and '" + EndDate + "')";
            //}

            strSql = "select * from (select row_number() over(order by StartDateTime desc) as rowNumber,* from V_CheduiContentSearch where isCheck=1 and  (CONVERT(nvarchar(11),StartDateTime,20) BETWEEN '" + StartDate + "' and '" + EndDate + "')";

            if (LoginUser.DepLevel == 0) //段级别登录
            {
                if (chedui == "0" || chedui == "1")  //0代表新打开页面
                {
                    //统计所有车队人员学习内容
                    //strSql += " AND DepPID=" + LoginUser.DepID.ToString();
                }
                else
                {
                    //统计所选车队人员学习内容
                    strSql += " AND DepID=" + chedui;
                }
            }
            else if (LoginUser.DepLevel == 1)  //车间级别登录
            {
                if (chedui == "0")
                {
                    //统计所有车队人员学习内容
                    strSql += " AND DepPID=" + LoginUser.DepID.ToString();
                }
                else
                {
                    //统计所选车队人员学习内容
                    strSql += " AND DepID=" + chedui;
                }
                
            }
            else if (LoginUser.DepLevel == 2)  //车队级别登录
            {
                //统计当前车队人员
                strSql += " AND DepID=" + LoginUser.DepID.ToString();
            }
            strSql += " ) TT ";

            strSqlpage = strSql + String.Format(" WHERE TT.rowNumber between {0} and {1}", startindex, endindex);

            try
            {

                int rowcount = 0;
                DataSet dscount = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().StudyContentSearch(strSql);
                if (dscount != null) {
                    if (dscount.Tables.Count > 0)
                    {
                        if (dscount.Tables[0].Rows.Count > 0)
                        {
                            rowcount = dscount.Tables[0].Rows.Count;
                        }
                    }
                }
                bool blExist = false;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().StudyContentSearch(strSqlpage);
                if (dsSearch != null)
                {
                    if (dsSearch.Tables.Count > 0)
                    {
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowcount;
                            blExist = true;
                        }
                    }
                }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText() + exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }


        /// <summary>
        /// 车间学习内容统计
        /// </summary>
        /// <param name="swhere"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainCourseFiles/ChejianStudyContentSearch")]
        public IHttpActionResult ChejianStudyContentSearch(string swhere, int page, int limit)
        {
            string StartDate = "";
            string EndDate = "";
            string chejian = "";
            //string searchLevel = "";
            if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
            {
                Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                swhere = string.Empty;
                foreach (var item in jsonObject)
                {
                    if (item.Key == "StartDate")
                    {
                        if (item.Value != "")
                            StartDate = item.Value;
                    }
                    if (item.Key == "EndDate")
                    {
                        if (item.Value != "")
                            EndDate = item.Value;
                    }
                    if (item.Key == "chejian")
                    {
                        if (item.Value != "")
                            chejian = item.Value;
                    }
                }
            }

            ResultMsg resultMsg = new ResultMsg();
            int startindex = (page - 1) * limit + 1;
            int endindex = page * limit;
            string strSql = "";
            string strSqlpage = "";

            string strSqlCount = "select count(*) from ";
            string strSqlpageHead = "select * from ";
            
            strSql = "(select row_number() over(order by TPReleaseStart desc) as rowNumber,* from V_ChejianContentSearch where TPReleaseStart>='"+StartDate+"' and TPReleaseEnd<='"+EndDate+"'";


            if (LoginUser.DepLevel == 0) //段级别登录
            {
                if (chejian == "0" || chejian == "")  //0代表新打开页面 
                {
                    //统计所有车队人员学习内容
                    //strSql += " AND DepPID=" + LoginUser.DepID.ToString();
                }
                else
                {
                    //统计所选车队人员学习内容
                    strSql += " AND DepID=" + chejian;
                }
            }
            else  //车间级别登录
            {
                    //统计所有车间学习内容
                    strSql += " AND DepID=" + LoginUser.DepID.ToString();
            }
            
            strSql += " ) TT ";

            strSqlpage = strSqlpageHead + strSql + String.Format(" WHERE TT.rowNumber between {0} and {1}", startindex, endindex);
            try
            {
                int rowcount = 0;
                rowcount = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().GetSqlCount(strSqlCount + strSql);
                
                bool blExist = false;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainCourseFiles().StudyContentSearch(strSqlpage);
                if (dsSearch != null)
                {
                    if (dsSearch.Tables.Count > 0)
                    {
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowcount;
                            blExist = true;
                        }
                    }
                }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText() + exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }


    }
}
